<?php
if( !class_exists('px_view') ){
	class px_view{
		var $styles = array();
		var $js = array();
		var $cssBasePath;
		var $cssBaseUrl;
		
		var $wpSiteUrl;
		
		var $jsBasePath;
		var $jsBaseUrl;
		
		var $baseFilePath;
		var $baseName;
		var $dirPath;
		var $dirName;
		var $uploaddir;
		var $uploaddirpath;
		var $imgBaseUrl;
		var $pluginUrl;
		
		var $imageGroup;
	
		function px_view($_file_){
			$this->baseFilePath = $_file_;
			$this->baseName = plugin_basename($_file_);
			$this->wpSiteUrl = get_bloginfo('wpurl');
			$this->dirPath = dirname($_file_);
			$this->views = $this->dirPath . '/common/views/';
			$this->uploaddir =  ABSPATH.get_option('upload_path').'/';
			$this->uploaddirpath =  $this->wpSiteUrl.'/'.get_option('upload_path').'/';
			$this->dirName = basename($this->dirPath);
			
			$this->pluginUrl = $this->wpSiteUrl . '?pxoption=';
			
			$this->cssBasePath = $this->dirPath . '/common/css/';
			$this->cssBaseUrl = $this->wpSiteUrl . '/wp-content/plugins/' . $this->dirName . '/common/css/';
			$this->jsUri = $this->wpSiteUrl . '/wp-content/plugins/' . $this->dirName . '/common/js/';
			
			$this->imgBaseUrl = $this->wpSiteUrl . '/wp-content/plugins/' . $this->dirName . '/common/img/';
			$this->swfBaseUrl= $this->wpSiteUrl . '/wp-content/plugins/' . $this->dirName .'/common/swf/';

			$this->jsBasePath = $this->dirPath . '/common/js/';
			$this->jsBaseUrl = $this->wpSiteUrl . '?pxoption=js&pxjs=';
			
			$this->galleryPluginUrl = $this->wpSiteUrl . '/wp-content/plugins/' . $this->dirName . '/plugins/';
			$this->galleryPluginDependencies = $this->wpSiteUrl . '/wp-content/plugins/' . $this->dirName . '/dependencies/';
			
			add_action('admin_menu', array(&$this, 'adminMenu'));

			unset($_file_);
		}// end: function px_view()	

		function loadCss(){
			if( !is_array( $this->styles ) ) return false;
			echo '<style>';
			foreach( $this->styles as $x ){
				echo '@import url( "'. $this->cssBaseUrl . $x . '");';
			}
			echo '</style>';
		}// end: function loadCss()
		
		function loadJs(){
			if( !is_array( $this->js ) ) return false;
			foreach( $this->js as $x ){
				wp_register_script('photoxhibit_'.$x, $this->jsBaseUrl . $x . '&'.time());
				wp_enqueue_script('photoxhibit_'.$x);
			}
			do_action('admin_print_scripts');
		}// end: function loadJs()
		

		function print_js( $which = NULL ){
			if($which == NULL) return;
			$this->vars = get_option('photoxhibit');
			$this->loadJSCode( $which );
		}
		
		function loadJSCode( $which ){
			//header('Content-type: application/javascript charset=utf-8');
			include_once($this->jsBasePath. $which . '.js'); 
		}

		function adminMenu(){
			$bp = $this->baseFilePath;
			if (function_exists('add_menu_page')) {
				add_menu_page('PhotoXhibit','PhotoXhibit', 7, $bp, array(&$this, 'showLandingPage'), $this->imgBaseUrl.'lphoto.png');
			}
			if (function_exists('add_submenu_page')) {
				add_submenu_page($bp, __('OverView', 'photoxhibit'), __('OverView', 'photoxhibit'), 7, $bp, array(&$this, 'showLandingPage'));
				add_submenu_page($bp, __('Manage Gallery', 'photoxhibit'), __('Manage Gallery', 'photoxhibit'), 7, 'px_manage', array(&$this, 'showGalleryManager'));
				add_submenu_page($bp, __('Build Gallery', 'photoxhibit'), __('Build Gallery', 'photoxhibit'), 7, 'px_build', array(&$this, 'showBuildGallery'));
			
				add_submenu_page($bp, __('Manage Album', 'photoxhibit'), __('Manage Album', 'photoxhibit'), 7, 'px_manageAlbum', array(&$this, 'adminManageAlbum'));

				add_submenu_page($bp, __('Options', 'photoxhibit'), __('Options', 'photoxhibit'), 7, 'px_options', array(&$this, 'showOptionsManager'));

				add_submenu_page($bp, __('About', 'photoxhibit'), __('About', 'photoxhibit'), 7, 'px_about', array(&$this, 'adminAbout'));
			}
		}  //  end : adminMenu()

/*
==================================================
*/
		function adminManageAlbum(){
			global $px_controller, $px_model, $wpdb;
			
			switch( $_GET['pxalbum_action'] ){
				case 'delete_album':
					$px_model->deleteAlbum();
					break;
				case 'manage_images':
					$this->styles = array('px.css','jquery-ui-themeroller.css');
					$this->js = array(
										'jquery','misc','jquery.metadata',
										'json','jquery-ui',
										'blockUI','swfupload',
										'swfupload.swfobject',
										'swfupload.queue','fileprogress',
										'handlers','swfuploadSetup', 'album_images'
									);
					$this->loadJs();
					$this->loadCss();
					
					$this->imageGroup = $px_model->get_photos_from_album();

					
					$this->loadView('px_admin_album_manager/px_admin_album_image_manager.php');
					return;
					break;
			}

			$this->styles = array('px.css');
			$this->js = array('jquery','jquery.metadata','json','jquery-ui','blockUI','misc','album');
			$this->loadJs();
			$this->loadCss();
			$this->loadView('px_admin_album_manager.php');
			
		}  //  end : adminManageAlbum()
/*
==================================================
*/

		/**
		 * @purpose: to help load views (html)
		 */
		function loadView($path = NULL){
			global $px_controller, $px_model, $wpdb, $phpFlickr;
			if ( $path == NULL ) return false;
			$full = $this->dirPath . '/common/views/' . $path;
			if ( !is_file( $full ) ) return false;
			include($full);
		}  //  end : function loadView
		
		function showLandingPage(){
			wp_admin_css( 'css/dashboard' );
			$this->styles = array('px.css');
			$this->js = array();
			$this->loadJs();
			$this->loadCss();
			$this->loadView('px_admin_landing.php');
		}
		
		function showBuildGallery(){
			global $px_controller, $px_model, $wpdb;

			$action = (string) $_GET['action'];
			$gid = (int) $_GET['pxgid'];
			
			if ( $gid ){
				$px_model->cur_gallery_id = $gid;
				$px_model->get_gallery_info();
				$px_model->get_imgs_group();
			}

			$this->styles = array('px.css');
			$this->js = array('jquery','jquery.metadata','json','jquery-ui','blockUI','misc','core');
			$this->loadJs();
			$this->loadCss();
			$this->loadView('px_admin_gallery_builder.php');
			
			/*
			echo '<h2>===========================</h2>';
			echo '<pre>';
			var_dump($px_controller);
			var_dump($px_model);
			var_dump($this);
			echo '</pre>';
			echo '<h2>===========================</h2>';
			*/
		}
		
		function get_css( $echo = false){
			global $px_controller, $px_model, $wpdb;
			
			if( $echo ) echo '<style type="text/css">';
			echo $px_model->cur_gallery_info->gallery_css;
			if( $echo ) echo '</style>';
		}
		
		function get_js( $echo = false ){
			global $px_controller, $px_model;
			$px_model->get_js_func();
			$path = $this->galleryPluginUrl;
			$path .= $px_controller->vars['plugin_cache'][$px_model->cur_gallery_info->plugin_id]['Path'];
			
			$js = $px_controller->vars['plugin_cache'][$px_model->cur_gallery_info->plugin_id]['Js'];
			$de = $px_controller->vars['plugin_cache'][$px_model->cur_gallery_info->plugin_id]['Dependencies'];
			
			$params = $px_controller->jsonDecode( $px_model->cur_gallery_info->gallery_params );
			
			$jsParam = array();
			if($params){
				foreach($params as $param => $k){
					$k = (is_numeric($k) || is_bool($k)) ? $k : '"'.$k.'"';
					array_push($jsParam, $param . ':' . $k);
				}
			}
			
			$js = explode(',', $js);
			$de = explode(',', $de);
			
			$del = count($de);
			for( $i = 0; $i < $del; $i++ ){
				if( preg_match('/jquery/', $de[$i]) && $_GET['page'] == 'px_build' ){}
				else{
					echo '<script type="text/javascript" src="'.$this->galleryPluginDependencies.$de[$i].'"></script>';
				}
			}
			
			$showA = '';
			//'a.'.$this->cur_js_func .',
			switch($this->cur_js_func){
				case 'lightBox':
				case 'lightboxbe':
				case 'thickbox':
					$selector = '#px'.$px_model->cur_gallery_info->gallery_id.' a';
					break;
				default:
					$selector = '#px'.$px_model->cur_gallery_info->gallery_id;
					break;
			}
			
			$jsl = count($js);
			for( $i = 0; $i < $jsl; $i++ ){
				echo '<script type="text/javascript" src="'.$path.'/'.$js[$i].'"></script>';
			}
			
			echo "\n\n".'<script type="text/javascript">(function($){$(document).ready(function(){$("'.$selector.'").'.$this->cur_js_func.'({'.join(',',$jsParam).'});});})(jQuery);</script>'."\n\n";
			
			//galleryPluginDependencies
			/*
			echo '<h2>===========================</h2>';
			echo '<pre>';
			//var_dump( get_defined_vars() );
			//var_dump($this->galleryPluginDependencies);
			//var_dump($path);
			echo '</pre>';
			echo '<h2>===========================</h2>';
			*/
		
		}
		
		function build_img_admin_list(){
			global $px_controller, $px_model, $wpdb;
			if(empty($px_model->cur_image_group)) return;
			$return = '';
			foreach ($px_model->cur_image_group as $result) {
				$return.= '<li><img alt="'.htmlentities($result->photo_alt).'" src="';
				$return .= $result->photo_tnurl;
				$return .= '" metadata="{'.htmlentities('"t":"'.$result->photo_tnurl.'","f":"'.$result->photo_url.'","a":"'.$result->photo_alt.'","i":'.$result->albumPhotos_id).'}"/></li>';
			}
			
			echo $return;
		}
		
		function build_img_structure(){
			global $px_controller, $px_model, $wpdb;
			$px_model->get_js_func();

			switch( $px_model->cur_gallery_info->gallery_structure ){
				case 0:
					$this->li_structure();
					break;
				case 1:
				case 2:
					$this->table_structure( true );
					break;
				case 3:
				case 4:
					$this->div_structure();
					break;
			}
		}
		
		function table_structure( $echo = false ){
			global $px_model;
			
			if(empty($px_model->cur_image_group)) return;
			
			$s = $px_model->cur_gallery_info->gallery_structure;

			$return .= '<table id="px'.$px_model->cur_gallery_info->gallery_id;
			$return .= '" title="'.htmlentities($px_model->cur_gallery_info->gallery_title,ENT_COMPAT, 'UTF-8');
			$return .= '" border="0" cellspacing="0" cellpadding="0">';
			$i = 1;
			$cols = $px_model->cur_gallery_info->gallery_extra;
			$total = count($px_model->cur_image_group);

			foreach ($px_model->cur_image_group as $result) {
				$title = htmlentities($result->photo_alt,ENT_COMPAT, 'UTF-8');

				if( $title == 'null' || $title == 'NULL' || $title == null || $title == NULL ){
					$title = '';
				}
				
				if(($i % $cols) == 1){
					$return .= "<tr>\n";
				}
				
				$return .= "<td>\n";
				
				$return .= '<a class="'.$this->cur_js_func.'" rel="g'.$this->cur_gallery_id.'" href="'.$result->photo_url;
				$return .= '" title="'.$title;
				$return .= '" alt="'.$title.'"><img src="';
				$return .= ($album_large) ? $result->photo_url : $result->photo_tnurl;
				$return .= '" metadata="'.encodeURIComponent('{"t":"'.$result->photo_tnurl.'","f":"'.$result->photo_url.'","a":"'.$title.'"}');
				$return .= '" alt="'.$title.'"/></a>';

				if( $s == 1 )
					$return .= '<p>'.$result->photo_alt.'</p>';
				
				$return .= "</td>\n";
	
				if(( $i % $cols ) == 0){
					$return .= "</tr>\n";
				}
				else if( $i == $total ){
					for($j = 1; $j <= ($cols-($total%$cols)); $j++){
						$return .= "<td>&nbsp;</td>\n";
					}
					$return .= "</tr>\n";			
				}
				$i++;
			}
			
			$return .= '</table>';
			
			if( $echo )
				echo $return;
			else
				return $return;
		}

		function li_structure(){
		}
		
		function div_structure(){
		}
		
		function showGalleryManager(){
			global $px_controller, $px_model, $wpdb;

			$action = (string) $_GET['action'];
			$gid = (int) $_GET['pxgid'];
			$px_model->cur_gallery_id = $gid;
			$this->js = array('jquery','misc');
			$this->styles = array('px.css');
			$this->loadJs();
			$this->loadCss();
			
			switch( $action ){
				// here we are going to edit the styles for a specific gallery
				case 'edit_styles':
					$px_model->get_imgs_group();
					// if everything is not good to proceed to viewing the manager page
					if( !$allIsGood ){
						$this->loadView('px_admin_gallery_edit_styles.php');
						exit(0);
					}
					break;
				// here we are going to be editing the data for each image that is in this gallery
				case 'edit_attrs':
					$px_model->cur_gallery_id = $gid;
					$px_model->get_gallery_info();
					$px_model->get_imgs_group();
					// if everything is not good to proceed to viewing the manager page
					if( !$allIsGood ){
						$this->loadView('px_admin_edit_image_attr.php');
						exit(0);
					}
					break;
				// here we are going to delete the gallery
				case 'delete_gallery':
					$px_model->delete_gallery( $gid );
					break;
					
			}
			
			// load out gallery manager page
			$this->loadView('px_admin_gallery_manager.php');
		}

		function showOptionsManager(){
			global $px_controller, $px_model, $wpdb, $phpFlickr;
			
			$this->styles = array('px.css');
			$this->js = array('jquery','json','misc','jquery-ui','options');
			$this->loadJs();
			$this->loadCss();
			$this->loadView('px_admin_options.php');
			
			/*
			echo '<h2>===========================</h2>';
			var_dump($this);
			echo '<h2>===========================</h2>';
			var_dump($px_controller);
			*/
		}

		function get_plugins_selectMenu($id=0){
			global $px_model,$px_controller;
			$results = $px_model->get_plugins();
			$return = '<select name="px_selectPlugin" id="px_selectPlugin"><option';
			$return .=  ' value="0"></option>';
			
			foreach ( $px_controller->vars['plugin_cache'] as $result => $value) {
				$return .= '<option value="'.$result.'" title="'.$value['plugin_example'];
				$return .= '" metadata="'.encodeURIComponent( $px_controller->jsonencode($value['Params']) ).'"';
				$return .= ($px_model->cur_gallery_info->plugin_id == $result) ? ' selected="selected" ':'';
				$return .= '>'.$value['Title'].'</option>';
			}
				
			if( $results ){
				$return .= '<option>-------------------------</option>';
				foreach ($results as $result) {
					$return.= '<option value="'.$result->plugin_id.'" title="'.$result->plugin_example.'" metadata="'.encodeURIComponent($result->plugin_params).'"';
					$return .= ($px_model->cur_gallery_info->plugin_id == $result->plugin_id) ? ' selected="selected" ':'';
					$return .= '>'.$result->plugin_title.'</option>';
				}
			}
			
			echo $return .= '</select>';
		}  //  end : get_galleries_selectMenu()
		
		function get_OptionTable(){
			global $wpdb, $px_model, $px_controller;
			
			$params 	= $px_model->cur_gallery_info->gallery_params;
			$plugin_id 	= $px_model->cur_gallery_info->plugin_id;

			$objs = $px_controller->jsonDecode(stripslashes($params));

			if( $plugin_id != 0 ){
				$sql = "SELECT * FROM ".$px_model->vars['plugins']." WHERE plugin_id = ".$wpdb->escape($plugin_id);
				$r = $wpdb->get_row($sql);
			}
			
			$galparams = $px_controller->jsonDecode( stripslashes( $r->plugin_params ) );
			
			
			if( !$r ){
				$plugin_params = $px_controller->vars['plugin_cache'][$plugin_id]['Params'];
				$galparams = $plugin_params;
			}


			$return = '';
			if($galparams->parameters){
				foreach ($galparams->parameters as $galparam => $v) {
					$return .= '<tr><td>'.$v->param.'</td><td><input type="text" size="30" name="'.$v->param.'"';
					$tmp = $v->param;
					$return .= ($objs->$tmp) ? ' value="'.$objs->$tmp.'" ' : '';
					$return .= '/></td><td>'.$v->desc.'</td></tr>';
				}
			}
			echo $return;
		}// end : get_OptionTable

	}//end : class px_view
}//end : if( !class_exists('px_view') )
?>